package com.boot.main.service.impl;

import com.boot.main.utils.IsNotEmptyUtil;
import com.boot.main.utils.Md5;
import com.boot.main.config.redis.JedisUtil;
import com.boot.main.entity.CcomUser;
import com.boot.main.jwt.JwtUtils;
import com.boot.main.mapper.CcomRoleMapper;
import com.boot.main.mapper.CcomUserMapper;
import com.boot.main.response.ResponseData;
import com.boot.main.response.ResponseDataUtil;
import com.boot.main.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UserService implements IUserService {
    @Resource
    private CcomUserMapper userMapper;
    @Resource
    private CcomRoleMapper roleMapper;

    @Override
    public ResponseData login(String username, String password, HttpServletResponse response) {
        log.info("用户登录");
        CcomUser ccomUser = userMapper.getUserToRoleByUserName(username);
        if(ccomUser != null){
            String[] roleIds = ccomUser.getRole_id().split(",");
            String[] roleNames = roleMapper.getRolesById(roleIds);
            ccomUser.setRole_name(String.join(",",roleNames));
            String dbpwd = ccomUser.getPassword();
            if(ccomUser.getUsername().equals(username)&& dbpwd.equals(password)){
                String token = JwtUtils.createJwtToken(username, 3600*24*10);
                log.info("登录时生成的token = " + token);
                long currentTimeMillis = System.currentTimeMillis();
                JedisUtil.setJson(username, token, 3600*24*10*1000);
//                Subject subject = SecurityUtils.getSubject();
//                UsernamePasswordToken utToken = new UsernamePasswordToken(username, token);
//                subject.login(utToken);

                HttpServletResponse httpServletResponse = response;
                httpServletResponse.setHeader("token", token);
                httpServletResponse.setHeader("Access-Control-Expose-Headers", "token");
                log.info("登录成功：" + ccomUser.toString());
                ccomUser.setPassword(dbpwd);
                Map<String, Object> map = new HashMap<>();
                map.put("user", ccomUser);
                map.put("accessToken", token);
                return ResponseDataUtil.success("登录成功", map);
            }
            return ResponseDataUtil.error("登录失败", null);
        }
        return ResponseDataUtil.error("登录失败, 用户不存在", null);
    }

    @Override
    public ResponseData otherLogin(CcomUser ccomUser, Integer type, HttpServletResponse response){
        //1 微信登录 2 H5 登录
        Md5 md5 = new Md5();
        if(type == 1){
            String unionid = ccomUser.getUnionid();
            if (IsNotEmptyUtil.isEmpty(unionid)){
                return ResponseDataUtil.error("获取的用户unionid为空", null);
            } else {
                CcomUser user = userMapper.getUserByUnionid(unionid);
                if(IsNotEmptyUtil.isEmpty(user)){
                    try {
                        ccomUser.setPassword(md5.GetMD5Code("888888"));
                        ccomUser.setCreate_time((new Date()).getTime());
                        Integer num = userMapper.saveUser(ccomUser);
                        if(IsNotEmptyUtil.isNotEmpty(num)){
                            String token = JwtUtils.createJwtToken(user.getUsername(), 3600*24*10);
                            Map<String, Object> map = new HashMap<>();
                            map.put("user", user);
                            map.put("accessToken", token);
                            return ResponseDataUtil.success("登录成功", map);
                        }
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    String token = JwtUtils.createJwtToken(user.getUsername(), 3600*24*10);
                    Map<String, Object> map = new HashMap<>();
                    map.put("user", user);
                    map.put("accessToken", token);
                    return ResponseDataUtil.success("登录成功", map);
                }
            }
        } else {
            CcomUser user1 = userMapper.getUserByUserName(ccomUser.getUsername());
            if(IsNotEmptyUtil.isEmpty(user1)){
                try {
                    ccomUser.setPassword(md5.GetMD5Code("888888"));
                    ccomUser.setCreate_time((new Date()).getTime());
                    Integer num = userMapper.saveUser(ccomUser);
                    if(IsNotEmptyUtil.isNotEmpty(num)){
                        String token = JwtUtils.createJwtToken(user1.getUsername(), 3600*24*10);
                        Map<String, Object> map = new HashMap<>();
                        map.put("user", user1);
                        map.put("accessToken", token);
                        return ResponseDataUtil.success("登录成功", map);
                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
            } else {
                String token = JwtUtils.createJwtToken(user1.getUsername(), 3600*24*10);
                Map<String, Object> map = new HashMap<>();
                map.put("user", user1);
                map.put("accessToken", token);
                return ResponseDataUtil.success("登录成功", map);
            }
        }
        return ResponseDataUtil.success("登录成功", null);
    }

    @Override
    public ResponseData logout(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        System.out.println(token);
        if(IsNotEmptyUtil.isEmpty(token)){
            return ResponseDataUtil.error("无效的token!", null);
        }
        token = token.substring(7);
        String username = JwtUtils.getUsername(token);
        System.out.println(username);
        CcomUser user = userMapper.getUserByUserName(username);
        // System.out.println(user);
        if(user != null){
            if(JedisUtil.getJson(username) == null){
                return ResponseDataUtil.error("已经退出登录过了!", null);
            }
            Long aLong = JedisUtil.delKey(username);
            return ResponseDataUtil.success("退出登录成功!", null);
        }
        return ResponseDataUtil.error("令牌失效，请重新登录！", null);
    }

    @Override
    public CcomUser getUserByUserName(String username){
        CcomUser user = userMapper.getUserByUserName(username);
        return user;
    }

    @Override
    public ResponseData getUsers(Integer page, Integer limit, String mobile, String username){
        List<CcomUser> items = userMapper.getUsers((page-1)*limit, limit, mobile, username);
        Integer count = userMapper.getTotalCount();
        Map map = new HashMap();
        map.put("datas", items);
        map.put("count", count);
        if(!items.isEmpty()){
            for (CcomUser item:items){
                String[] roleIds = item.getRole_id().split(",");
                String[] roleNames = roleMapper.getRolesById(roleIds);
                item.setRole_name(String.join(",",roleNames));
            }
            return ResponseDataUtil.success("查询成功", map);
        }
        return ResponseDataUtil.success("暂无用户信息！", map);
    }

    @Override
    public ResponseData saveUser(CcomUser item){
        int item_num = userMapper.saveUser(item);
        long item_id = item.getId();
        if(!IsNotEmptyUtil.isEmpty(item_num)) {
            return ResponseDataUtil.success( "新增用户成功！", null);
        } else {
            return ResponseDataUtil.error( "新增用户失败！", null);
        }
    }

    @Override
    public ResponseData saveFrontUser(CcomUser item){
        int item_num = userMapper.saveFrontUser(item);
        if(!IsNotEmptyUtil.isEmpty(item_num)) {
            return ResponseDataUtil.success( "新增用户成功！", null);
        } else {
            return ResponseDataUtil.error( "新增用户失败！", null);
        }
    }

    @Override
    public ResponseData updateUser(CcomUser item){
        int item_num = userMapper.updateUser(item);
        if(!IsNotEmptyUtil.isEmpty(item_num)) {
            return ResponseDataUtil.success( "修改用户成功！", null);
        } else {
            return ResponseDataUtil.error( "修改用户失败！", null);
        }
    }

    @Override
    public ResponseData updateUserMe(Map map, Long id){
        String name = map.get("name").toString();
        String avatar = map.get("avatar").toString();
        String sex = map.get("sex").toString();
        String mobile = map.get("mobile").toString();
        int item_num = userMapper.updateUserMe(name, avatar, sex, mobile, id);
        if(!IsNotEmptyUtil.isEmpty(item_num)) {
            return ResponseDataUtil.success( "修改用户成功！", null);
        } else {
            return ResponseDataUtil.error( "修改用户失败！", null);
        }
    }

    @Override
    public ResponseData deleteUser(Long id){
        int item_num = userMapper.deleteUser(id);
        if(!IsNotEmptyUtil.isEmpty(item_num)) {
            return ResponseDataUtil.success( "删除用户成功！", null);
        } else {
            return ResponseDataUtil.error("删除用户失败！", null);
        }
    }

    @Override
    public ResponseData resetPassword(Long id){
        Md5 md5 = new Md5();
        try {
            String password = md5.GetMD5Code("888888");
            int item_num = userMapper.resetPassword(password, id);
            if(IsNotEmptyUtil.isNotEmpty(item_num)){
                return ResponseDataUtil.success("重置密码成功", null);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseDataUtil.success("重置密码失败", null);
    }

    @Override
    public ResponseData updatePassword(Long id, String password, String newPassword){
        CcomUser user = userMapper.getUserById(id);
        String oldPassword = user.getPassword();
        if(!oldPassword.equals(password)) {
            return ResponseDataUtil.error("原密码不正确", null);
        }else {
            int item_num = userMapper.resetPassword(newPassword, id);
            if(IsNotEmptyUtil.isNotEmpty(item_num)){
                return ResponseDataUtil.success("修改密码成功", null);
            }
        }
        return ResponseDataUtil.success("修改密码失败", null);
    }
}
